<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/3
 * Time: 16:07
 */

namespace zframe\library;

use Exception;
use PDO;

class Db
{
	protected $options = [
		'dsn'      => '',
		'host'     => '127.0.0.1',
		'port'     => '3306',
		'dbname'   => 'zframe',
		'username' => 'root',
		'passwd'   => 'root',
		'prefix'   => 'zf_',
		'params'   => [],
	];//配置项
	
	/**
	 * @var PDO
	 */
	protected $pdo;
	
	/**
	 * @var \PDOStatement
	 */
	protected $pdoStatement;
	
	// PDO连接参数
	protected $params = [
		PDO::ATTR_CASE              => PDO::CASE_NATURAL,
		PDO::ATTR_ERRMODE           => PDO::ERRMODE_EXCEPTION,
		PDO::ATTR_ORACLE_NULLS      => PDO::NULL_NATURAL,
		PDO::ATTR_STRINGIFY_FETCHES => false,
		PDO::ATTR_EMULATE_PREPARES  => false,
	];
	
	protected $table;
	
	protected $fields;
	
	protected $where  = [];
	
	/**
	 * Db constructor.
	 * @param array $options
	 */
	public function __construct($options = [])
	{
		if (!empty($options)) {
			$options = array_merge($this->options, $options);
		} else {
			$options = $this->options;
		}
		// 连接参数
		if (isset($options['params']) && is_array($options['params'])) {
			$params = $options['params'] + $this->params;
		} else {
			$params = $this->params;
		}
		try {
			
			if (empty($options['dsn'])) {
				$options['dsn'] = "mysql:host=" . $options['host'] . ";port=" . $options['port'] . ";dbname=" . $options['dbname'];
			}
			
			$this->pdo = new PDO($options['dsn'], $options['username'], $options['passwd'], $params);
		} catch (\PDOException $e) {
			//链接失败
			die('连接失败');
		}
	}
	
	/**
	 * 设置表名
	 * @param $table
	 * @return $this
	 */
	protected function table($table)
	{
		$this->table = $this->getTableName($table);
		return $this;
	}
	
	protected function field($fields = "")
	{
		$this->fields = $fields;
		return $this;
	}
	
	protected function select()
	{
		$table = $this->table;
		
		$sql = "SELECT " . $this->fields . " FROM " . $table . " WHERE";
	}
	
	/**
	 * @param $field
	 * @param $operat
	 * @param $value
	 */
	protected function where($field, $op, $value)
	{
		if (is_array($field)) {
			$this->parseWhere($field);//->where(['name','zwp'])
		}
		$field = $field;//查询字段
		
	}
	
	/**
	 * 解析where查询
	 * @param array $where
	 */
	private function parseWhere(array $where)
	{
		foreach ($where as $k => $v) {
			if (count($v) > 2) {
				$this->where($v[0], $v[1], $v[2]);
			} else {
				$this->where($v[0], '=', $v[1]);
			}
		}
	}
	
	private function getTableName($name)
	{
		return $this->options['prefix'] . $name;
	}
	
	private function query($sql)
	{
		return $this->pdo->query($sql);
	}
	
	private function execute($sql)
	{
		return $this->pdo->exec($sql);
	}
}